package yagwl.server.fnd;

import java.util.logging.Logger;

import yagwl.service.util.svc.Context;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class AppEngineGwtRpcFilter extends AbstractFilter {
  private static Logger log = Logger.getLogger(AppEngineGwtRpcFilter.class
      .getName());
  protected UserService usrsvc;
  protected User user;

  @Override
  protected boolean isSenderAuthorized() {
    usrsvc = UserServiceFactory.getUserService();
    user = usrsvc.getCurrentUser();
    log.fine("No need to authorize sender");
    return true;
  }

  @Override
  protected boolean isUserLoggingOut(Context ctx) {
    return !usrsvc.isUserLoggedIn() && ctx.isUserLoggedIn();
  }

  @Override
  protected boolean isUserLoggingIn(Context ctx) {
    return usrsvc.isUserLoggedIn() && !ctx.isUserLoggedIn();
  }

  @Override
  protected boolean isUserLoggedIn(Context ctx) {
    return usrsvc.isUserLoggedIn() && ctx.isUserLoggedIn()
        && user.getUserId().equals(ctx.getUserId());
  }

  @Override
  protected boolean isUserIdMismatch(Context ctx) {
    return usrsvc.isUserLoggedIn() && ctx.isUserLoggedIn()
        && ! user.getUserId().equals(ctx.getUserId());
  }

  @Override
  protected void setUserIdInContext(Context ctx) {
    ctx.setUserId(user.getUserId());
  }

  @Override
  protected void setEmailInContext(Context ctx) {
    ctx.putAttribute(Context.Attr.Email.toString(), user.getEmail());
    setTransactionAuthorization(ctx); // TODO temporary code
  }

  @Override
  protected void setNicknameInContext(Context ctx) {
    ctx.putAttribute(Context.Attr.Nickname.toString(), user.getNickname());
  }

  @Override
  protected boolean isRequestAuthorized() {
    return true;
  }

  // temporary code
  private void setTransactionAuthorization(Context ctx) {
    boolean authorizeTxns = false;
    String email = ctx.getAttributeStr(Context.Attr.Email.toString());
    if (email.equals("joydeep@gmail.com"))
      authorizeTxns = true;
    ctx.putAttribute("AuthorizeTransactions", Boolean.toString(authorizeTxns));
  }

}
